package com.thtf.homework.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5 {

    /**
     * 使用MD5算法对字符串进行加密
     *
     * @param plainText 明文
     * @return MD5加密后的字符串
     */

    public static String encrypt(String plainText) {
        try {
            // 创建MD5加密对象
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 对字符串进行加密，返回加密后的字节数组
            byte[] mdBytes = md.digest(plainText.getBytes());
            // 将加密后的字节数组转换为十六进制字符串
            StringBuilder hexValue = new StringBuilder();
            for (byte b : mdBytes) {
                int val = ((int) b) & 0xff;
                if (val < 16) {
                    hexValue.append("0");
                }
                hexValue.append(Integer.toHexString(val));
            }
            return hexValue.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

//    测试
//    public static void main(String[] args) {
//        String originalString = "Hello, World!";
//        String md5Result = encrypt(originalString);
//        System.out.println("原文: " + originalString);
//        System.out.println("MD5加密后: " + md5Result);
//    }
}